package com.dxb.test.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * ClassName：com.dxb.test.thread.CyclicBarrierABC <br>
 * Description：CyclicBarrier <br>
 *
 * @author 戴晓波 <br>
 * Date 2022/2/14/014 17:02 <br>
 * @version v1.0 <br>
 */
public class CyclicBarrierABC {


    static void print(CyclicBarrier current, CyclicBarrier next) {
        try {
            for (int i = 0; i < 10; i++) {
                //一进来就卡住，等待前一个线程的await
                current.await();
                System.out.println(Thread.currentThread().getName());
                //让下一个线程从await中醒来
                next.await();
            }
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //CyclicBarrier是state=0就是继续运行线程，这里设置为2，
        // 一开始，所有线程都await，等待前面个线程await了才能执行，主线程await任一一个，就打破平衡
        CyclicBarrier barrierA = new CyclicBarrier(2);
        CyclicBarrier barrierB = new CyclicBarrier(2);
        CyclicBarrier barrierC = new CyclicBarrier(2);
        new Thread(() -> print(barrierA, barrierB), "A").start();
        new Thread(() -> print(barrierB, barrierC), "B").start();
        new Thread(() -> print(barrierC, barrierA), "C").start();
        try {
            barrierA.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
